#include "NMenuWindow.h"
#include "../../../Util/MyStrUtil.h"

NMenuWindow::NMenuWindow() : NWindow(80, LINES, 0, 0, true)
{
    offset = 0;
    showNumbers = false;
    selected = 0;
    menuWidth = 0;
    keypad(window, true);
    x = 0;
    y = 0;
}

void NMenuWindow::center()
{
    if (showNumbers)
        menuWidth += 3;
    y = (LINES - choices.size())  / 2;
    x = (COLS - menuWidth) / 2;
}

int NMenuWindow::getChoice()
{
    show();
    while (true)
    {
        chtype c = wgetch(window);
        switch(c)
        {
            case KEY_UP:
            {
                if (selected > 0)
                {
                    --selected;
                    redraw();
                }
                break;
            }
            case KEY_DOWN:
            {
                if (selected < choices.size() - 1)
                {
                    ++selected;
                    redraw();
                }
                break;
            }
            case 10: // Enter key pressed
            {
                return selected;
            }
        }
    }
}

void NMenuWindow::show()
{
    if (! visible)
    {
        visible = true;
        redraw();
    }
}

void NMenuWindow::setShowNumbers(bool newSetting)
{
    if (newSetting)
        offset = 3;
    else
        offset = 0; 
        
    showNumbers = newSetting;
}

void NMenuWindow::redraw()
{
    for (unsigned int i = 0; i < choices.size(); ++i)
    {
        if (selected == i)
            wattron(window, A_REVERSE);
            
        if (showNumbers)
        {
            printString(x, y + i, myNtoStr<int>(i + 1));
            printString(x + 1, y + i, ") ");
        }
        printString(x + offset, y + i, choices[i]);
        wattroff(window, A_REVERSE);
    }
    refresh();
}

void NMenuWindow::setLocation(Point newLocation)
{
    location = newLocation;
}

void NMenuWindow::setChoices(vector<string> newChoices)
{
    menuWidth = 0;
    for (unsigned int i = 0; i < newChoices.size(); ++i)
    {
        if (newChoices[i].size() > menuWidth)
            menuWidth = newChoices[i].size();
    }
    choices = newChoices;
} 

void NMenuWindow::addChoice(string newChoice)
{
    if (newChoice.size() > menuWidth)
        menuWidth = newChoice.size();
        
    choices.push_back(newChoice);
}

NMenuWindow::~NMenuWindow()
{
}
